<?php
/**
 * 事务详情页面
 */
require_once '../../includes/header.php';

// 检查用户是否已登录
if (!isLoggedIn()) {
    header('Location: /login.php');
    exit;
}

// 获取事务ID
$taskId = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($taskId <= 0) {
    $_SESSION['error_message'] = '无效的事务ID';
    header('Location: /views/task/list.php');
    exit;
}

// 获取事务信息
$taskObj = new Task();
$task = $taskObj->getTask($taskId);

// 检查事务是否存在
if (!$task) {
    $_SESSION['error_message'] = '事务不存在';
    header('Location: /views/task/list.php');
    exit;
}

// 检查用户是否有权限查看此事务（创建者或参与者）
$isCreator = ($task['creator_id'] == $_SESSION['user_id']);
$isParticipant = $taskObj->isTaskParticipant($taskId, $_SESSION['user_id']);

if (!$isCreator && !$isParticipant) {
    $_SESSION['error_message'] = '您没有权限查看此事务';
    header('Location: /views/task/list.php');
    exit;
}

// 获取创建者信息
$userObj = new User();
$creator = $userObj->getUserById($task['creator_id']);

// 获取参与者列表
$participants = $taskObj->getTaskParticipants($taskId);

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 完成事务
    if (isset($_POST['complete_task'])) {
        $result = $taskObj->completeTask($taskId, $_SESSION['user_id']);
        if ($result['status']) {
            $_SESSION['success_message'] = $result['message'];
            header('Location: /views/task/detail.php?id=' . $taskId);
            exit;
        } else {
            $error_message = $result['message'];
        }
    }
    
    // 增加亲密度
    if (isset($_POST['increase_intimacy'])) {
        $friendId = intval($_POST['friend_id']);
        $result = $taskObj->increaseIntimacy($taskId, $_SESSION['user_id'], $friendId);
        if ($result['status']) {
            $_SESSION['success_message'] = $result['message'] . '，增加了' . $result['points'] . '点亲密度';
            header('Location: /views/task/detail.php?id=' . $taskId);
            exit;
        } else {
            $error_message = $result['message'];
        }
    }
    
    // 接受邀请
    if (isset($_POST['accept_invitation'])) {
        $result = $taskObj->acceptTaskInvitation($taskId, $_SESSION['user_id']);
        if ($result['status']) {
            $_SESSION['success_message'] = $result['message'];
            header('Location: /views/task/detail.php?id=' . $taskId);
            exit;
        } else {
            $error_message = $result['message'];
        }
    }
    
    // 拒绝邀请
    if (isset($_POST['reject_invitation'])) {
        $result = $taskObj->rejectTaskInvitation($taskId, $_SESSION['user_id']);
        if ($result['status']) {
            $_SESSION['success_message'] = $result['message'];
            header('Location: /views/task/list.php');
            exit;
        } else {
            $error_message = $result['message'];
        }
    }
}

// 获取通知消息
$success_message = $_SESSION['success_message'] ?? null;
unset($_SESSION['success_message']);

// 获取当前用户的参与状态
$currentUserStatus = 'none';
foreach ($participants as $participant) {
    if ($participant['id'] == $_SESSION['user_id']) {
        $currentUserStatus = $participant['status'];
        break;
    }
}

// 检查是否可以增加亲密度
$canIncreaseIntimacy = false;
$intimacyAdded = false;
if ($task['status'] == 'completed') {
    foreach ($participants as $participant) {
        if ($participant['id'] == $_SESSION['user_id'] && $participant['intimacy_added'] == 0) {
            $canIncreaseIntimacy = true;
        }
        if ($participant['id'] == $_SESSION['user_id'] && $participant['intimacy_added'] == 1) {
            $intimacyAdded = true;
        }
    }
}

// 获取男友列表（用于增加亲密度）
$friendObj = new Friend();
$friends = [];
if ($canIncreaseIntimacy) {
    $allFriends = $friendObj->getFriendList($_SESSION['user_id']);
    
    // 只保留参与此事务的男友
    foreach ($allFriends as $friend) {
        if ($friend['id'] == $task['creator_id'] || $taskObj->isTaskParticipant($taskId, $friend['id'])) {
            $friends[] = $friend;
        }
    }
}

// 格式化状态文本
$statusText = '';
$statusClass = '';
switch ($task['status']) {
    case 'pending':
        $statusText = '待完成';
        $statusClass = 'bg-warning';
        break;
    case 'completed':
        $statusText = '已完成';
        $statusClass = 'bg-success';
        break;
    case 'expired':
        $statusText = '已过期';
        $statusClass = 'bg-danger';
        break;
}
?>

<div class="container mt-4">
    <div class="row">
        <div class="col-md-8 offset-md-2">
            <div class="card">
                <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                    <h4 class="mb-0">事务详情</h4>
                    <span class="badge <?php echo $statusClass; ?>"><?php echo $statusText; ?></span>
                </div>
                <div class="card-body">
                    <?php if (isset($success_message)): ?>
                        <div class="alert alert-success"><?php echo $success_message; ?></div>
                    <?php endif; ?>
                    
                    <?php if (isset($error_message)): ?>
                        <div class="alert alert-danger"><?php echo $error_message; ?></div>
                    <?php endif; ?>
                    
                    <!-- 事务信息 -->
                    <div class="mb-4">
                        <h5 class="card-title"><?php echo htmlspecialchars($task['title']); ?></h5>
                        <p class="card-text">
                            <?php if (!empty($task['description'])): ?>
                                <?php echo nl2br(htmlspecialchars($task['description'])); ?>
                            <?php else: ?>
                                <em>无描述</em>
                            <?php endif; ?>
                        </p>
                        <div class="d-flex justify-content-between">
                            <small class="text-muted">
                                创建者: 
                                <img src="<?php echo getUserAvatar($creator['avatar']); ?>" alt="<?php echo $creator['nickname'] ?? $creator['username']; ?>" class="rounded-circle" width="20" height="20">
                                <?php echo $creator['nickname'] ?? $creator['username']; ?>
                            </small>
                            <small class="text-muted">
                                创建时间: <?php echo date('Y-m-d H:i', strtotime($task['created_at'])); ?>
                            </small>
                        </div>
                        <div class="mt-2">
                            <span class="badge bg-info">
                                截止时间: <?php echo date('Y-m-d H:i', strtotime($task['deadline'])); ?>
                            </span>
                            
                            <?php if ($task['status'] == 'pending'): ?>
                                <?php
                                $deadlineTime = strtotime($task['deadline']);
                                $currentTime = time();
                                $remainingSeconds = $deadlineTime - $currentTime;
                                
                                if ($remainingSeconds > 0) {
                                    $days = floor($remainingSeconds / 86400);
                                    $hours = floor(($remainingSeconds % 86400) / 3600);
                                    
                                    if ($days > 0) {
                                        $timeRemaining = "剩余 {$days} 天 {$hours} 小时";
                                    } else {
                                        $minutes = floor(($remainingSeconds % 3600) / 60);
                                        $timeRemaining = "剩余 {$hours} 小时 {$minutes} 分钟";
                                    }
                                ?>
                                    <span class="badge bg-warning text-dark">
                                        <?php echo $timeRemaining; ?>
                                    </span>
                                <?php } ?>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <!-- 参与者列表 -->
                    <div class="mb-4">
                        <h5>参与者</h5>
                        <?php if (count($participants) > 0): ?>
                            <div class="list-group">
                                <?php foreach ($participants as $participant): ?>
                                    <div class="list-group-item d-flex justify-content-between align-items-center">
                                        <div>
                                            <img src="<?php echo getUserAvatar($participant['avatar']); ?>" alt="<?php echo $participant['nickname'] ?? $participant['username']; ?>" class="rounded-circle me-2" width="30" height="30">
                                            <?php echo $participant['nickname'] ?? $participant['username']; ?>
                                        </div>
                                        <?php
                                        $participantStatusText = '';
                                        $participantStatusClass = '';
                                        switch ($participant['status']) {
                                            case 'invited':
                                                $participantStatusText = '已邀请';
                                                $participantStatusClass = 'bg-info';
                                                break;
                                            case 'accepted':
                                                $participantStatusText = '已接受';
                                                $participantStatusClass = 'bg-primary';
                                                break;
                                            case 'rejected':
                                                $participantStatusText = '已拒绝';
                                                $participantStatusClass = 'bg-danger';
                                                break;
                                            case 'completed':
                                                $participantStatusText = '已完成';
                                                $participantStatusClass = 'bg-success';
                                                break;
                                        }
                                        ?>
                                        <span class="badge <?php echo $participantStatusClass; ?>">
                                            <?php echo $participantStatusText; ?>
                                        </span>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-info">
                                此事务没有其他参与者
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- 操作按钮 -->
                    <div class="d-grid gap-2">
                        <?php if ($task['status'] == 'pending'): ?>
                            <?php if ($isParticipant && $currentUserStatus == 'invited'): ?>
                                <!-- 受邀请的参与者可以接受或拒绝 -->
                                <div class="d-flex gap-2">
                                    <form method="POST" action="" class="flex-grow-1">
                                        <button type="submit" name="accept_invitation" class="btn btn-success w-100">接受邀请</button>
                                    </form>
                                    <form method="POST" action="" class="flex-grow-1">
                                        <button type="submit" name="reject_invitation" class="btn btn-danger w-100">拒绝邀请</button>
                                    </form>
                                </div>
                            <?php elseif (($isCreator || ($isParticipant && $currentUserStatus == 'accepted'))): ?>
                                <!-- 创建者或已接受的参与者可以完成事务 -->
                                <form method="POST" action="">
                                    <button type="submit" name="complete_task" class="btn btn-primary">标记为已完成</button>
                                </form>
                            <?php endif; ?>
                        <?php endif; ?>
                        
                        <a href="/views/task/list.php" class="btn btn-outline-secondary">返回事务列表</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php require_once '../../includes/footer.php'; ?>
